package com.yuchao.springboot.handler;

import com.google.common.collect.Maps;
import com.yuchao.springboot.annotation.HandlerType;
import com.yuchao.springboot.utils.ClassScaner;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @description:
 * @author: xingyuchao
 * @date: 2019-11-07
 */
@Component
public class HandlerProcessor implements BeanFactoryPostProcessor{

    private static final String HANDLER_PACKER = "com.yuchao.springboot.handler.biz";

    /**
     * 扫描@HandlerType，初始化HandlerContext，将其注册到spring容器
     * @param configurableListableBeanFactory
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        Map<String,Class> handlerMap = Maps.newHashMapWithExpectedSize(3);

        ClassScaner.scan(HANDLER_PACKER,HandlerType.class).forEach(clazz ->{
            // 获取注解中的类型值
            String type = clazz.getAnnotation(HandlerType.class).value();
            // 将注解中的类型值作为key，对应的类作为value，保存在Map中
            handlerMap.put(type, clazz);
        });

        HandlerContext context = new HandlerContext(handlerMap);

        configurableListableBeanFactory.registerSingleton(HandlerContext.class.getName(),context);
    }
}
